/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);

var deptId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId);
var isChildren = 1; // todo 1：包含子部门，2：不包含子部门
var sexMap = new Map();
//表格初始化配置
var tableInit = function () {

    var columns = [
        {
            title: '全选',
            field: 'select',
            //复选框
            checkbox: true,
            width: 25,
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'id',
            title: 'ID',
            align: 'center',
            width: 30,
            sortable: true,
            visible: false
        }, {
            field: 'headerImgUrl',
            title: '头像',
            align: 'center',
            formatter: function (value) {
                if (!empty(value)) {
                    var img_html = "<a href='" + value + "' title='点击查看大图' target='_blank'>" +
                        "<img src='" + value + "' width='40' onerror='imgNotfind(event);' /></a>";
                    return img_html;
                } else {
                    return "<img src='" + value + "' width='40' onerror='imgNotfind(event);' />";
                }
            }
        }, {
            field: 'name',
            title: '名称',
            align: 'center',
            sortable: false
        }, {
            field: 'sex',
            title: '性别',
            align: 'center',
            sortable: false,
            formatter: function (value) {
                return sexMap.get(value.toString());
            }
        }, {
            field: 'deptName',
            title: '部门',
            align: 'center',
            sortable: false
        }, {
            field: 'stationName',
            title: '职位',
            align: 'center',
            sortable: false
        }, {
            field: 'wxTel',
            title: '微信关联电话',
            align: 'center',
            visible: true
        }, {
            field: 'phone',
            title: '常用电话',
            align: 'center',
            visible: false
        }, {
            field: 'wxCode',
            title: '微信号',
            align: 'center',
            visible: false,
        }, {
            field: 'wxImgUrl',
            title: '微信二维码',
            align: 'center',
            formatter: function (value) {
                if (!empty(value)) {
                    var img_html = "<a href='" + value + "' title='点击查看大图' target='_blank'>" +
                        "<img src='" + value + "' width='40' onerror='imgNotfind(event);' /></a>";
                    return img_html;
                } else {
                    return "<img src='" + value + "' width='40' onerror='imgNotfind(event);' />";
                }
            }
        }, {
            field: 'gmtCreate',
            title: '创建时间',
            align: 'center',
            sortable: false,
            visible: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        }, {
            field: 'gmtModified',
            title: '修改时间',
            align: 'center',
            sortable: false,
            visible: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        },
    ];

    //请求服务数据时所传参数
    function queryParams(params) {
        return {
            pageNumber: params.pageNumber,
            pageSize: params.pageSize,
            searchText: params.searchText,
            sortName: params.sortName,      //排序列名
            sortOrder: params.sortOrder, //排位命令（desc，asc）
            isChildren: isChildren,
            deptId: deptId
        }
    }

    var tableConfig = $.extend(bootstrapTableConfig(_HOST + _API.business_manage_staff_list, queryParams, columns), {
        //这里是其他的一些个性化的 bootstrap-table options
        //例如 覆盖一些公共的配置
        //例如 添加一些私有的配置
        showColumns: true,//列显示操作按钮
        ajaxOptions: { //设置自定义请求头
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': 'staff:list'
            }
        },
        //例如格式化数据
        responseHandler: function (res) {
            //在ajax获取到数据，渲染表格之前，修改数据源
            //console.log(res)
            if (res.success) {
                //更新本地token
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.token, res.token);
            }
            return res;
        }
    });
    //调用实例化
    $('#bootstrapTableEvents').bootstrapTable(tableConfig);
    $(".search input").attr('placeholder', '姓名/部门/职位/手机号/微信号');
};

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['staff:add', 'staff:update', 'staff:del', 'department:list'],
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);

            return;
        }
        that.getDictionary()
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        //获取字典表配置数据
        getDictionary: function () {
            var that = this;
            var params = "?keyTable=sex";
            Get(that, _HOST + _API.common_dic_dicList + params)
                .then(function (response) {
                    // 响应成功回调
                    //console.log(response)
                    if (response) {
                        if (response.success) {
                            var list = response.list;
                            for (var item in list) {
                                sexMap.set(list[item].keyS.toString(), list[item].keyValue.toString())
                            }
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    //初始化设置zTree
                    that.initTree();
                })
        },
        // 确定
        del: function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var ids = "";
            for (let i = 0; i < list.length; i++) {
                ids += list[i].loginId;
                if ((i + 1) != list.length) {
                    ids += ",";
                }
            }
            console.log(ids);
            Post(that, _HOST + _API.business_cardPosterModel_personAdd + "?modelId=" + aGET.modelId + "&staffIds=" + ids + "&companyId=" + companyId, {}, true, '')
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            window.parent.location.reload(); //刷新父页面
                            layer.msg(response.msg, {time: 1500, icon: 1});
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                });
        },
        //是否包含子部门员工点击事件
        isChildrenf: function () {
            if (1 == isChildren) {
                isChildren = 2;
            } else {
                isChildren = 1;
            }
            $('#bootstrapTableEvents').bootstrapTable('refresh');
        },
        //初始化部门树
        initTree: function () {
            var that = this;
            var loadingIndex = layer.load(2, { //icon支持传入0-2
                shade: [0.5, 'gray'], //0.5透明度的灰色背景
                content: '数据加载中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                }
            });
            var setting = {
                check: {
                    enable: false,
                    chkStyle: "radio",
                    radioType: "all"   //对所有节点设置单选
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentId",
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: function (e, treeId, treeNode, clickFlag) {
                        console.log(treeNode)
                        deptId = treeNode.id;
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        zTreee.checkNode(treeNode, !treeNode.checked, true);
                    }
                },
            }, zTreee;
            var zNodes = [];
            Get(that, _HOST + _API.business_manage_sysDepartment_list + "/" + deptId, that.permissions[3])
                .then(function (response) {
                    // 响应成功回调
                    //console.log(response)
                    if (response) {
                        if (response.success) {
                            zNodes = response.list;
                            deptId = zNodes[0].id;
                            //初始化表格
                            tableInit();

                            zTreee = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");

                            var nodes = treeObj.getNodes();
                            if (nodes.length > 0) {
                                for (var i = 0; i < nodes.length; i++) {
                                    treeObj.expandNode(nodes[i], true, false, false);//默认展开第一级节点
                                }
                            }
                            layer.close(loadingIndex);
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        }
    },
});

/**
 * 是否包含子部门员工点击事件
 */
$("#isChildren input:checkbox[name='isChildren']").on('ifChecked', function (event) {
    app.isChildrenf();
});
$("#isChildren input:checkbox[name='isChildren']").on('ifUnchecked', function (event) {
    app.isChildrenf();
});
